package com.oneToone.byPK.service;

import com.oneToone.byPK.model.Address;
import com.oneToone.byPK.model.Customer;
import com.utils.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class BusinessService {
    private HibernateUtil hibernateUtil = new HibernateUtil();
    private SessionFactory sessionFactory = hibernateUtil.getSessionFactory();

    private void saveCustomer(Customer customer) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            System.out.println();
            tx = session.beginTransaction();
            session.save(customer);
            tx.commit();

        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            session.close();
        }
    }

    private Customer loadCustomer(Long id) {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Customer customer = (Customer) session.get(Customer.class, id);
            tx.commit();

            return customer;

        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            session.close();
        }
    }

    private void printCustomer(Customer customer) {
        Address address = customer.getAddress();
        System.out.println("Address of " + customer.getName() + " is: "
                + address.getProvince() + " "
                + address.getCity() + " "
                + address.getStreet());

        if (address.getCustomer() == null)
            System.out.println("Can not naviagte from address to Customer.");

    }

    private void test() {

        Customer customer = new Customer();
        Address address = new Address("province1", "city1", "street1", "100001", customer);
        customer.setName("Tom");
        customer.setAddress(address);

        saveCustomer(customer);
        customer = loadCustomer(customer.getId());
        printCustomer(customer);
        sessionFactory.close();

    }

    public static void main(String args[]) {
        new BusinessService().test();
    }
}


